import json
import re
from django import http
from django.shortcuts import render


from django.views import View
from django_redis import get_redis_connection



# 5重置密码
from apps.ausers.models import User
from apps.verifications import constants
from meiduo_mall.settings.dev import logger
from utils.cookiesecret import CookieSecret
from utils.response_code import RETCODE


class PwdSetView(View):
    def post(self, request, user_id):
        # 获取参数
        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        access_token = CookieSecret.loads(json_dict.get('access_token'))

        # 校验参数
        if not all([password, password2]):
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('密码最少8为,最长20位')
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')

        # 修改密码
        try:
            user = User.objects.get(id=user_id)
            user.set_password(password)
            user.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('密码更改失败')
        # # 保持登陆
        # login(request, user)
        # response = redirect(reverse('users:login'))
        # response.delete_cookie('username')
        #
        #
        # response.set_cookie('username', user.username, max_age=14*3600*24)
        #
        # # 合并购物车
        # response = merge_cart_cookie_to_redis(request=request, user=user, response=response)
        # # 响应修改密码结果:重定向到登陆界面
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


# 4短信验证码验证
class SmsCodeCheckView(View):
    def get(self, request, username):
        # 获取参数
        sms_code = request.GET.get('sms_code')

        # 检验sms_code是否存在
        if not all([username, sms_code]):
            return http.HttpResponseForbidden('缺少必传参数')

            # 判断用户是否存在
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseForbidden('用户不存在')
        mobile = user.mobile
        # 判断手机号是否存在
        if not mobile:
            return http.HttpResponseNotFound('手机号不存在')

        # 校验短信验证码
        client_redis = get_redis_connection('sms_code')
        sms_code_redis = client_redis.get('sms_%s' % mobile)
        if sms_code_redis is None:
            return http.HttpResponseBadRequest('验证码错误')
        if sms_code != sms_code_redis.decode():
            return http.HttpResponseBadRequest('验证码错误')

        user_id = user.id
        access_token = {
            'username': username,
            'userid': user_id
        }
        access_token_str = CookieSecret.dumps(access_token)

        return http.JsonResponse({'user_id': user_id, 'access_token': access_token_str})


# 3.获取短信验证码
class SmsCodeGetView(View):
    def get(self, request, celery_tasks=None):
        # 获取参数

        mobile = CookieSecret.loads(request.GET.get('access_token'))['mobile']
        try:
            # sms_code = get_sms_code(mobile)
            from random import randint
            sms_code = '%06d' % randint(0, 999999)
            sms_redis_client = get_redis_connection('sms_code')
            # 防止频繁发送短息
            send_flag = sms_redis_client.get('send_flag_%s' % mobile)
            if send_flag:
                return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '短信发送太频繁'})

            pl = sms_redis_client.pipeline()
            pl.setex('send_flag_%s' % mobile, constants.SENG_SMS_CODE_INTERVAL, 1)
            pl.setex('sms_%s' % mobile, constants.IMAGE_CODE_REDIS_EXPIRES, sms_code)
            pl.execute()
            # from celery_tasks.sms.tasks import ccp_send_sms_code
            # ccp_send_sms_code.delay(mobile, sms_code)
            print('验证码是:', sms_code)
        except Exception as e:
            return http.HttpResponseForbidden('短信验证码获取失败')
        return http.JsonResponse({'message': '验证码已经发送'})


# 2.验证用户是否存在
class AccountsView(View):
    def get(self, request, username):
        # 获取参数
        uuid = request.GET.get('image_code_id')
        image_code = request.GET.get('text')
        # 判断参数是否齐全
        if not all([username, image_code]):
            return http.HttpResponseForbidden('参数缺失')
            # 校验参数是否符合格式
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden("用户名格式错误")
            # 校验图形验证码是否正确
        client_redis = get_redis_connection('verify_image_code')
        redis_img_code = client_redis.get('img_%s' % uuid)

        if not redis_img_code:
            return http.HttpResponseBadRequest('验证码错误')
            # 如果有值 删除redis服务器上的图像验证码
        try:
            client_redis.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)
            # 和前端传过来的值进行比较
        if image_code != redis_img_code.decode().lower():
            return http.HttpResponseBadRequest('验证码错误')

            # 判断用户是否存在
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseNotFound('手机号错误')

            # 获取用户手机号
        mobile = user.mobile
        # 生成access_token
        access_token = {
            'mobile': mobile,
            'username': username,
        }
        # 加密access_token
        access_token_str = CookieSecret.dumps(access_token)

        return http.JsonResponse({'code': RETCODE.OK,
                                  'mobile': mobile,
                                  'access_token': access_token_str})


    # 1.显示找回密码页面


# 1.显示找回密码页面
class FindPasswordView(View):
    def get(self, request):
        return render(request, 'find_password.html')